﻿using System;
using System.IO;

namespace Cannonball
{
    class WordsDictionary
    {
        private string[] words;
        private Random rand;
        private int[] lengthIndexes;

        public WordsDictionary()
        {
            this.words = File.ReadAllLines(@"../../newWordsFile.txt"); //this.words = File.ReadAllLines(@"../../wordsEn.txt"); <-- original version
            Array.Sort(words, (x, y) => x.Length.CompareTo(y.Length));
            IndexWords();
        }
        private void IndexWords()
        {
            this.lengthIndexes = new int[words[words.Length - 1].Length]; // Last word is longest
            int currentLength = 0;                              //original --> this.lengthIndexes = new int[words[words.Length - 1].Length - 1];
            for (int i = 0; i < this.words.Length; i++)         //had to change it because it was throwing an IndexOutOfRangeException
            {
                if (this.words[i].Length > currentLength)
                {
                    this.lengthIndexes[currentLength] = i - 1;
                    currentLength = this.words[i].Length;
                }
            }
        }
        // Get random word
        public string GetRandomWord()
        {
            rand = new Random();
            int start = rand.Next(2, words.Length);
            return this.words[start];
        }
        // Get random word with fixed length
        public string GetRandomWord(int length)
        {
            if (length <= 1)
            {
                throw new Exception("Length must be positive integer greater than one.");
            }

            this.rand = new Random();
            int index = this.rand.Next(this.lengthIndexes[length - 1], this.lengthIndexes[length] - 1);
            return this.words[index];
        }
        // Get random word with length in a range
        public string GetRandomWord(int minLength, int maxLength)
        {
            if (minLength <= 1)
            {
                throw new Exception("Length must be positive integer greater than one.");
            }
            else if (maxLength > lengthIndexes.Length - 1)
            {
                throw new Exception("Length must be smaller than" + lengthIndexes.Length + ". ");
            }
            else if (minLength > maxLength)
            {
                throw new Exception("Invalid parameters");
            }

            rand = new Random();
            int index = rand.Next(this.lengthIndexes[minLength - 1], this.lengthIndexes[maxLength] - 1);
            return this.words[index];
        }
    }
}
